package com.tinyideatech.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tinyideatech.common.utils.StrUtil;
import com.tinyideatech.common.utils.StringUtils;
import com.tinyideatech.system.entity.SysRole;
import com.tinyideatech.system.entity.SysRoleMenu;
import com.tinyideatech.system.entity.SysUser;
import com.tinyideatech.system.entity.SysUserRole;
import com.tinyideatech.system.mapper.SysUserMapper;
import com.tinyideatech.system.mapper.SysUserRoleMapper;
import com.tinyideatech.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser selectByUsername(String username) {
        List<SysUser> userList = super.list(new QueryWrapper<SysUser>().eq("username", username));
        if(userList.size() > 0){
            return userList.get(0);
        }
        return null;
    }

    @Override
    public void changeStatus(SysUser user) {
        SysUser sysUser = getById(user.getUserId());
        if(sysUser != null){
            sysUser.setStatus(user.getStatus());
            updateById(user);
        }
    }

    @Override
    public List<SysUserRole> setUserRoleList(SysUser user) {
        Long[] roleIds = StrUtil.toLongArray(",", user.getRoleIds());
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long roleId : roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(user.getUserId());
            list.add(userRole);
        }
        return list;
    }

    @Override
    public String getRoleIds(SysUser user) {
        List<SysUserRole> userRoleList = userRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", user.getUserId()));
        List<Long> idList = new ArrayList<>();
        for(SysUserRole userRole: userRoleList){
            idList.add(userRole.getRoleId());
        }
        return StringUtils.join(idList, ",");
    }

}
